/**
 * Storage封装
 * 所有session都存储在mall值下
 */
const STORAGE_KEY = 'mall';

export default {
  //  存储值[任意类型]
  setItem(key, value, moduleName) {
    if (moduleName) {
      let val = this.getItem(moduleName);
      val[key] = value;
      this.setItem(moduleName, val);
    } else {
      let val = this.getStorage();
      val[key] = value;
      window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val));
    }
  },
  //获取某一个模块下面的属性，如user下面的userName
  //user下面的userName
  getItem(key, moduleName) {
    if (moduleName) {
      // 返回一个对象
      let val = this.getItem(moduleName);
      if (val) {
        return val[key];
      }
    }
    return this.getStorage()[key];
  },
  // 获取所有数据
  getStorage() {
    return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY));
  },
  // 清空某一个值
  clear(key, moduleName) {
    let val = this.getStorage();
    if(moduleName){
      if(val[moduleName]){
        delete val[moduleName][key];
      }
    } else {
      delete val[key];
    }
    window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val));
  }
}
